package cn.seaboot.admin.rabbit.test;

import org.eclipse.paho.client.mqttv3.*;

/**
 * 接收 MQTT 消息
 *
 * @author Mr.css
 * @version 2024-10-15 9:16
 */
public class MqttReceiver implements MqttCallback {
    public static void main(String[] args) {
        try {
            String topic = "mqtt";
//            String broker = "tcp://localhost:1883";
            String broker = "tcp://47.122.57.10:1883";
            String clientId = "MQTTReceiver";

            MqttClient client = new MqttClient(broker, clientId);
            MqttCallback callback = new MqttReceiver();

            client.setCallback(callback);

            // 使用自定义参数连接
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName("root");
            options.setPassword("root".toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);

            // 不清除会话，重启的时候，可以获取到断线期间的消息，这个配置非常重要
            options.setCleanSession(false);
            client.connect(options);

            int qos = 2;
            client.subscribe(topic, qos);

            //
            // client.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void connectionLost(Throwable cause) {
        // 当连接丢失时调用
        System.out.println("Connection lost");
        cause.printStackTrace();
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // 当接收到消息时调用
        System.out.println("Message arrived: " + new String(message.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        // 当消息发送成功时调用
        System.out.println("Delivery complete");
    }
}